# coding=utf-8

from flask import render_template, redirect, url_for, flash, current_app
from flask_login import login_required

from app.routes.setting import bp
from app.routes.setting.forms import EmailSettingForm
from app.models import EmailSetting, Project
from app.utils.util import exception_handle
from app.cores.dictionaries import STATUS


@bp.route('/basic_setting', methods=['GET', 'POST'])
@login_required
def basic_setting():
    form = EmailSettingForm()
    email_setting = EmailSetting.get_current_email_setting()
    projects = Project.query.filter_by(status=STATUS.NORMAL).all()
    if form.validate_on_submit():
        try:
            if email_setting:
                email_setting.update(
                    whether_send_email=True if form.whether_send_email.data.lower() == 'true' else False,
                    whether_gen_report=True if form.whether_gen_report.data.lower() == 'true' else False,
                    email_title=form.email_title.data,
                    email_text=form.email_text.data,
                    receiver_address=form.receiver_address.data,
                )
            else:
                EmailSetting.add(
                    whether_send_email=True if form.whether_send_email.data.lower() == 'true' else False,
                    whether_gen_report=True if form.whether_gen_report.data.lower() == 'true' else False,
                    email_title=form.email_title.data,
                    email_text=form.email_text.data,
                    receiver_address=form.receiver_address.data,
                )
        except Exception as e:
            exception_handle(current_app, e)
            flash('更新失败，请查看日志', category='error')
        else:
            flash('更新成功')
        return redirect(url_for('setting.basic_setting'))  # TODO util增加一个方法可以自动刷新当前页面
    if email_setting:
        form.whether_send_email.data = str(email_setting.whether_send_email).lower()
        form.whether_gen_report.data = str(email_setting.whether_gen_report).lower()
        form.email_title.data = email_setting.email_title
        form.email_text.data = email_setting.email_text
        form.receiver_address.data = email_setting.receiver_address
    else:
        form.whether_send_email.data = None
        form.whether_gen_report.data = None
        form.email_title.data = None
        form.email_text.data = None
        form.receiver_address.data = None
    return render_template('setting/basic_setting.html', form=form, projects=projects)
